﻿using System;
using System.Data;
using Core.Log;
using UnityEngine;
using UnityEngine.InputSystem;

namespace Game {
    /// <summary>
    /// 2D玩家控制器
    /// Author：TuJacky
    /// Time：2023年10月4日15:16:25
    /// </summary>
    public class PlayerController : PlayerModule {
        public Vector2 HandDirection {
            get;
            private set;
        }

        public Transform Hand {
            get {
                return mHand.transform;
            }
        }
        
        private Transform mArm;
        private Transform mHand;
        [SerializeField] private float force = 1.0f;

        //移动控制器
        private IMoveController mMoveController;

        public PlayerController(Player player) : base(player) { }

        public override void Init() {
            mArm = mPlayer.Component.Arm;
            mHand = mPlayer.Component.Hand;
            GameInput.Ins.NormalInput.Enable();
            GameInput.Ins.CombatInput.Enable();
            mMoveController = new ColliderMoveController(mPlayer.PlayerObj.GetComponent<Collider2D>(), mPlayer.Component.Filter);
            mPlayer.Component.OnPlayerUpdate += onUpdate;
        }

        public override void Release() {
            mPlayer.Component.OnPlayerUpdate -= onUpdate;
        }

        private void onUpdate() {
            moveHandle();
            handMoveHandle();
        }

        private void moveHandle() {
            Vector2 direction = GameInput.Ins.NormalInput.Move.ReadValue<Vector2>();
            mMoveController.Move(direction, mPlayer.PlayerData.Speed, mPlayer.PlayerData.Acceleration);
        }

        private void handMoveHandle() {
            Vector2 mousePosition = CameraUtils.GetCombatMousePosition();
            Vector2 playerPosition = (Vector2)mPlayer.PlayerObj.transform.position;
            HandDirection = ((Vector2)mousePosition - playerPosition).normalized;

            Vector3 normal = Vector3.Cross(Vector3.right, HandDirection);
            float handAngle = Vector2.Angle(Vector2.right, HandDirection);
            handAngle *= (handAngle == 180 ? 1 : MathF.Sign(Vector3.Dot(normal, Vector3.forward)));
            mArm.eulerAngles = handAngle * Vector3.forward;
            //修正手的位置
            float handDistance = Vector2.Distance(mousePosition, playerPosition);
            var newHandPos = mHand.transform.localPosition;
            newHandPos.x = Mathf.Clamp(handDistance, .0f, mPlayer.PlayerData.HandDistance);
            mHand.transform.localPosition = newHandPos;
            Vector3 handScale = Vector3.one;
            handScale.y = Mathf.Abs(handAngle) <= 90 ? 1 : -1;
            mHand.transform.localScale = handScale;
        }
    }
}